package com.tnsw.facebookautoliker.helper.command;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Settings;
import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsList;
import com.tnsw.facebookautoliker.database.SelfPosts;
import com.tnsw.facebookautoliker.database.SelfPostsLike;
import com.tnsw.facebookautoliker.database.VSelfPostsLike;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;
import com.tnsw.facebookautoliker.services.AutoLikerService;

public class GetSelfPost extends FacebookCommandObject implements Request.Callback, FQLInterface {

	private DBManager dbm;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
	
	public GetSelfPost(Context context) {
		super(context);
		super.tag = "GetSelfPost";
		
		this.dbm = DBManager.getInstance(this.context);
	}
	
	@Override
	public void execute() {
		super.execute();
		
		MyLog.d(tag, "GetSelfPost executing..");
		
		if (MyLog.isProduction == false) {
			Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
		}
		
		Session session = Session.openActiveSessionFromCache(this.context);
		if (session != null) {
			AutoLikerService aService = AutoLikerService.getInstance();
			String path = aService.getSelfInfo().id + "/posts";
			
			Request req = new Request(session, path, null, HttpMethod.GET);
			req.setCallback(this);
			this.standardExecute(req);				
		}
		
	}
	
	@Override
	protected void handleResult(Response response) {
		super.handleResult(response);
		
		if (response != null) {

			JSONObject jo = response.getGraphObject().getInnerJSONObject();
			try {
				JSONArray jaData = jo.getJSONArray("data");
				if (jaData != null) {
					int len = jaData.length();
					int i;
										
					for (i = 0; i < len; i++) {
						boolean canLike = false;
						
						JSONObject jData = jaData.getJSONObject(i);
						String post_id = jData.getString("id");
						
						if (jData.has("actions")) {
							JSONArray jaActions = jData.getJSONArray("actions");
							int j;
							for (j = 0; j < jaActions.length(); j++) {
								JSONObject jActions = jaActions.getJSONObject(j);
								if (jActions.has("name")) {
									String name = jActions.getString("name");
									if (name.equals("Like")) canLike = true;
								}
							}
							
						}
						
						long created = -1;
						
						if (jData.has("created_time")) {
							String created_time = jData.getString("created_time");
							try {
								Calendar cc = Calendar.getInstance();						
								cc.setTime(this.sdf.parse(created_time));	
								created = cc.getTimeInMillis();
							} catch (Exception e) {
								MyLog.e(tag, "Cannot parse created_time=" + created_time);
							}
								
						}
						
						
						MyLog.d(tag, i + ":post_id=" + post_id + ", canLike=" + canLike);
						
						SelfPosts sp = null;
						if (canLike == true) {
							ArrayList<RecordBase> a = this.dbm.getRecords(SelfPosts.class.getName(), "select * from self_posts where post_id=?", new String[] {post_id}, 0);
							if (a == null) {
								// This is new Post from this user
								sp = new SelfPosts();
								sp.primarykey = this.dbm.getNewPrimarykey();
								sp.post_id = post_id;
								sp.created = created;
								
								long r = this.dbm.insertRecord("self_posts", sp, null, true);
								MyLog.d(tag, "inserted new self_posts(r=" + r + ")");
							} else {
								sp = (SelfPosts) a.get(0);
								MyLog.d(tag, "found exissting self_posts");
							}
							
							this.likePostId(post_id, sp.primarykey, created);
						}
					}
				}				
			} catch (Exception e) {
				MyLog.e(tag, "handleResult - " + e.toString(), e);
			}

		}
		
	}
	
	private void likePostId(String postId, int self_posts, long post_created) {
		FQLBase fqlb = new FQLBase(this.context, null);
		String fql = "select user_id from like where post_id='" + postId + "'";
		fqlb.setPagingColumn(null);
		fqlb.setFQL(fql);
		fqlb.setLimit(50);
		fqlb.setTag("command", "like_postid");
		fqlb.setTag("post_id", postId);
		fqlb.setTag("self_posts", self_posts);
		fqlb.setTag("self_post_created", post_created);
		fqlb.setFQLInterface(this);
		
		GeneralManager gm = GeneralManager.getInstance();
		gm.addNewQueue(fqlb, 2);
	}

	@Override
	public void onCompleted(Response response) {
		this.handleResult(response);
		
	}

	@Override
	public boolean onSingleRecordFetched(Object sender, int recordNo, JSONObject jo) {
		return false;
	}

	@Override
	public void onEndQuery(Object sender, ArrayList<JSONObject> arrJ) {
		FQLBase fqlb = (FQLBase) sender;
		
		if (arrJ != null) {
			int len = arrJ.size();
			int i;
			for (i = 0; i < len; i++) {
				JSONObject jLike = arrJ.get(i);
				try {
					String user_id = jLike.getString("user_id");
					String post_id = (String) fqlb.getTag("post_id");
					int self_posts = (Integer) fqlb.getTag("self_posts");
					long post_created = (Long) fqlb.getTag("self_post_created");
					
					ArrayList<RecordBase> a = this.dbm.getRecords(VSelfPostsLike.class.getName(), "select * from v_self_posts_like where post_id=? and userid=?", new String[] {post_id, user_id}, 0);
					if (a == null) {
						// This user never like this post_id before
						SelfPostsLike sp = new SelfPostsLike();
						sp.primarykey = this.dbm.getNewPrimarykey();
						sp.created = System.currentTimeMillis();
						sp.userid = user_id;
						sp.self_posts = self_posts;
						
						long r = this.dbm.insertRecord("self_posts_like", sp, null, true);
						if (r != -1) {
							// increase counter
							ArrayList<RecordBase> aa = this.dbm.getRecords(FriendsList.class.getName(), "select * from friends_list where id=?", new String[] {user_id}, 0);
							if (aa != null) {
								FriendsList fl = (FriendsList) aa.get(0);
								fl.like_me_count += 1;
								if (fl.like_me_count_since == 0) {
									fl.like_me_count_since = post_created;
								} else if (post_created != -1) {
									if (post_created < fl.like_me_count_since) {
										fl.like_me_count_since = post_created;
									}
								}
								
								AutoLikerService aService = AutoLikerService.getInstance();
								aService.updateFriendsList(fl.id, fl);
								this.dbm.updateRecordByPrimarykey("friends_list", fl, true);
								
								MyLog.d(tag, "updated like_me_count");
							} else {
								MyLog.e(tag, "Cannot find userid=" + user_id + ", may be some other like me but not in friends_list");
							}
						}
												

					} else {
						MyLog.d(tag, "this userid=" + user_id + " liked and recorded already");
					}
				} catch (Exception e) {
					MyLog.e(tag, "onEndQuery - " + e.toString(), e);
				}
				
			}
		}
	}

}
